package com.dny.asmtop.op;

import com.dny.asmtop.Command;
import com.dny.asmtop.MethodContext;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.GeneratorAdapter;

import java.util.Objects;

import static jdk.internal.org.objectweb.asm.Type.getType;

/**
 * Created by jlutt on 2018-01-17.
 * 设置数组某个项的值
 * @author jlutt
 */
public class CommandArraySet implements Command {

  /**
   * 数组对象
   */
  private Command array;

  /**
   * 索引
   */
  private Command position;

  /**
   * 值
   */
  private Command item;

  public CommandArraySet(Command array, Command position, Command item) {
    this.array = array;
    this.position = position;
    this.item = item;
  }

  @Override
  public Type type(MethodContext context) {
    return Type.VOID_TYPE;
  }

  @Override
  public Type generator(MethodContext context) {
    GeneratorAdapter g = context.getGeneratorAdapter();

    array.generator(context);
    position.generator(context);
    item.generator(context);

    g.arrayStore(getType(array.type(context).getDescriptor().substring(1)));
    return Type.VOID_TYPE;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CommandArraySet that = (CommandArraySet) o;
    return Objects.equals(array, that.array) &&
        Objects.equals(position, that.position) &&
        Objects.equals(item, that.item);
  }

  @Override
  public int hashCode() {

    return Objects.hash(array, position, item);
  }
}
